package com.hmall.service;

import com.hdmall.business.common.common.ServerResponse;
import com.hmall.mapper.*;
import com.hmall.model.MallDealer;
import com.hmall.model.MallOrder;
import com.hmall.model.SysCustomer;
import com.hmall.model.SysUser;
import com.hmall.vo.*;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.*;

/**
 * @ClassName BiService
 * @Description
 * @Author zhoutao
 * @Date 2018/12/18 9:20
 * @Version 2.0
 **/
@Service
@Slf4j
public class BiService {


    private final
    MallDealerMapper mallDealerMapper;

    private final
    SysUserMapper sysUserMapper;

    private final
    SysCustomerMapper sysCustomerMapper;

    private final
    MallOrderMapper mallOrderMapper;

    private final
    MallOrderItemMapper mallOrderItemMapper;

    private final
    SysDeptCustomerMapper sysDeptCustomerMapper;

    @Autowired
    public BiService(MallDealerMapper mallDealerMapper, SysUserMapper sysUserMapper, SysCustomerMapper sysCustomerMapper, MallOrderMapper mallOrderMapper, SysDeptCustomerMapper sysDeptCustomerMapper, MallOrderItemMapper mallOrderItemMapper) {
        this.mallDealerMapper = mallDealerMapper;
        this.sysUserMapper = sysUserMapper;
        this.sysCustomerMapper = sysCustomerMapper;
        this.mallOrderMapper = mallOrderMapper;
        this.sysDeptCustomerMapper = sysDeptCustomerMapper;
        this.mallOrderItemMapper = mallOrderItemMapper;
    }

    /**
     * @Date 2018/12/18 9:31
     * @Param [user]
     * @return com.hmall.common.ServerResponse
     * @Description  得到业务员和办事处的筛选条件
     */
    public ServerResponse getFilterList(SysUser user) {

        List<BiFilterVo> biFilterVoList = new ArrayList<>();

        MallDealer mallDealer = mallDealerMapper.selectAllByDeptId(user.getDeptId());
        biFilterVoList.add(new BiFilterVo(1, user.getRealName(), user.getUserId()));
        biFilterVoList.add(new BiFilterVo(2, mallDealer.getDealerName(), mallDealer.getDealerId()));
        return ServerResponse.createBySuccess(biFilterVoList);
    }

    /**
     * @Date 2018/12/18 9:51
     * @Param [type, id]
     * @return com.hmall.common.ServerResponse
     * @Description  根据办事处或者业务员得到bi信息
     *
     */
    public ServerResponse<BiDataVo> getBiData(Integer type, Integer id, Integer year, Integer month) {

        //type 是 2表示办事处 1表示是业务员
        Integer dealerType = 2;
        Integer salesmanType = 1;
        //得到业务员列表
        List<Integer> salesmanUserIdList = new ArrayList<>();
        if(dealerType.equals(type)){
            salesmanUserIdList = sysUserMapper.selectSalesmanListByDealerId(id);
        }else if(salesmanType.equals(type)){
            salesmanUserIdList.add(id);
        }

        //做一些初始数据使用
        List<SysCustomer> customerList = new ArrayList<>();
        List<Integer> customerUserIdList = new ArrayList<>();
        //根据业务员得到所有的公司列表
        if(salesmanUserIdList != null && salesmanUserIdList.size() != 0){
            customerList = sysCustomerMapper.selectAllBySalesmanIdList(salesmanUserIdList);
        }
        //根据公司列表得到公司的人员
        if(customerList != null && customerList.size() != 0) {
            customerUserIdList = sysDeptCustomerMapper.selectCustomerUserIdListByCustomerList(customerList);
        }

        List<MallOrder> mallOrderList = getMallOrderList(year, month, customerUserIdList);
        assert customerList != null;
        return ServerResponse.createBySuccess(getBiDataByCustomerUserIdList(customerUserIdList,  customerList, mallOrderList));
    }

    /**
     * @Date 2018/12/18 17:37
     * @Param [year, month, customerUserIdList]
     * @return java.util.List<com.hmall.model.MallOrder>
     * @Description  根据用户得到订单列表
     */
    private List<MallOrder> getMallOrderList(Integer year, Integer month, List<Integer> customerUserIdList){
        //得到这个月的订单列表
        Date startTime, endTime;
        Calendar calendar = Calendar.getInstance();
        calendar.set(year, month - 1, 1, 0, 0, 0);
        startTime = calendar.getTime();
        calendar.add(Calendar.MONTH, 1);
        endTime = calendar.getTime();


        List<MallOrder> mallOrderList = mallOrderMapper.selectOrderByTime(startTime, endTime, customerUserIdList);
        return mallOrderList;
    }



    /**
     * @Date 2018/12/18 12:49
     * @Param [customerUserIdList, mallOrderList]
     * @return com.hmall.common.ServerResponse<com.hmall.vo.BiDataVo>
     * @Description  得到信息数据
     */
    private BiDataVo getBiDataByCustomerUserIdList(List<Integer> customerUserIdList, List<SysCustomer> customerList, List<MallOrder> mallOrderList) {


        BiDataVo biDataVo = new BiDataVo();

        //设置客户信息
        assert customerList != null;
        biDataVo.setBiCustomerVo(getBiCustomerVo(customerUserIdList, customerList.size(), mallOrderList));
        log.info("客户信息设置成功");

        //设置客户交易信息
        biDataVo.setBiCustomerTradeVoList(getBiCustomerTradeVoList(customerList, mallOrderList));
        log.info("客户交易信息设置成功");

        //设置产品信息
        biDataVo.setBiProductVoList(getBiProductVo(mallOrderList));
        log.info("产品信息设置成功");
        BiTradeVo biTradeVo = getBiTradeVo(mallOrderList);

        //设置交易重量信息
        biDataVo.setBiTradeWeightVoList(biTradeVo.getBiTradeWeightVoList());
        log.info("交易重量设置成功");

        //设置交易价格信息
        biDataVo.setBiTradePaymentVoList(biTradeVo.getBiTradePaymentVoList());
        log.info("交易价格信息设置成功");

        //设置交易客单量信息
        biDataVo.setBiTradeGuestVoList(biTradeVo.getBiTradeGuestVoList());
        log.info("交易客单价设置成功");
        return biDataVo;
    }


    /**
     * @Date 2018/12/18 10:43
     * @Param [customerUserIdList]
     * @return com.hmall.vo.BiCustomerVo
     * @Description  得到客户信息
     */
    private BiCustomerVo getBiCustomerVo(List<Integer> customerUserIdList, Integer customerSize, List<MallOrder> mallOrderList){
//        ConcurrentHashMap
        BiCustomerVo biCustomerVo = new BiCustomerVo();

        //1.公司数目
        biCustomerVo.setCustomerTotalNumber(customerSize);
        Set<Integer> set = new HashSet<>();

        for(MallOrder mallOrder : mallOrderList){
            if(customerUserIdList.contains(mallOrder.getUserId())){
                set.add(mallOrder.getUserId());
            }
        }
        //根据这些用户得到公司信息
        List<Integer> userIdList = new ArrayList<>(set);
        set.clear();

        //2.交易的公司数目
        //根据用户得到公司信息
        Integer customerNumber = 0;
        if(userIdList.size() != 0) {
            customerNumber = sysDeptCustomerMapper.selectCustomerCountByCustomerUserIdList(userIdList);
        }
        biCustomerVo.setCustomerTradeNumber(customerNumber);

        //3.成交总额
        BigDecimal totalPrice = new BigDecimal(0.0);
        //4.成交总总量
        BigDecimal totalWeight = new BigDecimal(0.0);
        if(mallOrderList.size() != 0){
            totalPrice = mallOrderItemMapper.selectTotalPriceByOrder(mallOrderList);
            totalWeight = mallOrderItemMapper.selectTotalWeightByOrder(mallOrderList);
        }

        biCustomerVo.setTradeTotalPayment(totalPrice);
        biCustomerVo.setTradeTotalWeight(totalWeight);
        return biCustomerVo;
    }

    /**
     * @Date 2018/12/18 13:31
     * @Param [customerUserIdList, mallOrderList]
     * @return java.util.List<com.hmall.vo.BiCustomerTradeVo>
     * @Description  得到公司交易信息
     */
    private List<BiCustomerTradeVo> getBiCustomerTradeVoList(List<SysCustomer> customerList, List<MallOrder> mallOrderList) {

        List<BiCustomerTradeVo> biCustomerTradeVoList = new ArrayList<>();

        //公司数目很少
        for(SysCustomer sysCustomer:customerList){
            BiCustomerTradeVo biCustomerTradeVo = new BiCustomerTradeVo();
            biCustomerTradeVo.setCustomerId(sysCustomer.getCustomerId());
            biCustomerTradeVo.setCustomerName(sysCustomer.getBusName());

            BigDecimal totalTradePayment = new BigDecimal(0.0);
            BigDecimal totalTradeWeight = new BigDecimal(0.0);
            if(mallOrderList != null && mallOrderList.size() != 0) {
                totalTradePayment = mallOrderMapper.selectTotalTradePaymentByCustomerId(sysCustomer.getCustomerId(), mallOrderList);
                totalTradeWeight = mallOrderMapper.selectTotalTradeWeightByCustomerId(sysCustomer.getCustomerId(), mallOrderList);
            }
            if(totalTradePayment == null && totalTradeWeight == null) {
                continue;
            }
            if(totalTradePayment != null && totalTradePayment.intValue() == 0 && totalTradeWeight != null && totalTradeWeight.intValue() == 0){
                continue;
            }

            biCustomerTradeVo.setTotalTradePayment(totalTradePayment);
            biCustomerTradeVo.setTotalTradeWeight(totalTradeWeight);
            biCustomerTradeVoList.add(biCustomerTradeVo);
        }

        return biCustomerTradeVoList;
    }

    /**
     * @Date 2018/12/18 13:48
     * @Param [mallOrderList]
     * @return com.hmall.vo.BiProductVo
     * @Description  得到产品信息
     */
    private List<BiProductVo> getBiProductVo(List<MallOrder> mallOrderList) {

        List<BiProductVo> biProductVoList = new ArrayList<>();
        BigDecimal dtyCount, fdyCount, poyCount, otherCount, hoyCount;
        if(mallOrderList != null && mallOrderList.size() != 0) {
            //找到DTY
            dtyCount = mallOrderItemMapper.selectCountByTypeAndOrderList("DTY", mallOrderList);
            if(dtyCount != null && dtyCount.intValue() != 0E-8){
                biProductVoList.add(new BiProductVo("DTY", dtyCount));
            }
            //找到FDY
            fdyCount = mallOrderItemMapper.selectCountByTypeAndOrderList("FDY", mallOrderList);
            if(fdyCount != null && fdyCount.intValue() != 0E-8){
                biProductVoList.add(new BiProductVo("FDY", fdyCount));
            }
            //找到HOY
            hoyCount = mallOrderItemMapper.selectCountByTypeAndOrderList("HOY", mallOrderList);
            if(hoyCount != null && hoyCount.intValue() != 0E-8){
                biProductVoList.add(new BiProductVo("HOY", hoyCount));
            }
            //找到POY
            poyCount = mallOrderItemMapper.selectCountByTypeAndOrderList("POY", mallOrderList);
            if(poyCount != null && poyCount.intValue() != 0E-8){
                biProductVoList.add(new BiProductVo("POY", poyCount));
            }
            //找到其他类型
            otherCount = mallOrderItemMapper.selectOtherCountByTypeAndOrderList(mallOrderList);
            if(otherCount != null && otherCount.intValue() != 0E-8){
                biProductVoList.add(new BiProductVo("Other", otherCount));
            }
        }
        return biProductVoList;
    }

    /**
     * @Date 2018/12/18 14:09
     * @Param [mallOrderList]
     * @return java.util.List<com.hmall.vo.BiTradeWeightVo>
     * @Description   得到一个月之内交易总量信息
     */
    private BiTradeVo getBiTradeVo(List<MallOrder> mallOrderList) {
        List<BiTradeWeightVo> biTradeWeightVoList = new ArrayList<>();
        List<BiTradePaymentVo> biTradePaymentVoList = new ArrayList<>();
        List<BiTradeGuestVo> biTradeGuestVoList = new ArrayList<>();

        //时间->订单编号列表
        Calendar calendar = Calendar.getInstance();
        Map<Integer, List<Long>> map = new HashMap<>(40);
//        List<Long> newList = new ArrayList<>();

        //将订单分组
        for(MallOrder mallOrder : mallOrderList){
            Date createTime = mallOrder.getCreateTime();
            calendar.setTime(createTime);
            Integer date = calendar.get(Calendar.DAY_OF_MONTH);
            if(map.containsKey(date)){
                List<Long> newList = map.get(date);
                newList.add(mallOrder.getOrderNo());
                map.put(date,newList);
            }else{
                List<Long> newList = new ArrayList<>();
                newList.add(mallOrder.getOrderNo());
                map.put(date, newList);
            }
        }


        //封装时间和重量参数
        //每一天都要进行sql查询很低效..
        for(Map.Entry entry : map.entrySet()){
            Integer date = (Integer) entry.getKey();
            //肯定不为空
            List<Long> orderNoList = (List<Long>) entry.getValue();
            BigDecimal totalQuantity = mallOrderItemMapper.selectTotalWeightByOrderNoList(orderNoList);
            BigDecimal totalPayment = mallOrderItemMapper.selectTotalPriceByOrderNoList(orderNoList);

            //日重量
            BiTradeWeightVo biTradeWeightVo = new BiTradeWeightVo(date, totalQuantity);
            if(totalQuantity.intValue() != 0 && totalQuantity.intValue() != 0E-8) {
                biTradeWeightVoList.add(biTradeWeightVo);
            }
            //日价格
            BiTradePaymentVo biTradePaymentVo = new BiTradePaymentVo(date, totalPayment);
            if(totalPayment.intValue() != 0 && totalPayment.intValue() != 0E-8) {
                biTradePaymentVoList.add(biTradePaymentVo);
            }
            //客单价 = 一天的交易额/交易的笔数目
            //一个OrderNo 就是一个笔数
            if(totalPayment.intValue() == 0){
                totalPayment = new BigDecimal(0.0);
            }

            if(totalPayment.intValue() == 0){
                totalPayment = new BigDecimal(0.0);
            }else{
                totalPayment = totalPayment.divide(BigDecimal.valueOf(orderNoList.size()), 2);
            }
            BiTradeGuestVo biTradeGuestVo = new BiTradeGuestVo(date, totalPayment);
            biTradeGuestVoList.add(biTradeGuestVo);
        }

        BiTradeVo biTradeVo = new BiTradeVo(biTradeWeightVoList, biTradePaymentVoList, biTradeGuestVoList);
        return biTradeVo;

    }

    /**
     * @Date 2018/12/18 16:40
     * @Param [type, id, year, month, productType]
     * @return com.hmall.common.ServerResponse
     * @Description  根据产品类型得到产品售卖的信息
     */
    public ServerResponse<List<SpecialNameAndWeightVo>> getProductDetail(Integer type, Integer id, Integer year, Integer month, String productType) {

        List<Integer> salesmanUserIdList = new ArrayList<>();
        if(type == 2){
            salesmanUserIdList = sysUserMapper.selectSalesmanListByDealerId(id);
        }else if(type == 1){
            salesmanUserIdList.add(id);
        }

        //做一些初始数据使用
        List<SysCustomer> customerList = new ArrayList<>();
        List<Integer> customerUserIdList = new ArrayList<>();
        //根据业务员得到所有的公司列表
        if(salesmanUserIdList != null && salesmanUserIdList.size() != 0){
            customerList = sysCustomerMapper.selectAllBySalesmanIdList(salesmanUserIdList);
        }
        //根据公司列表得到公司的人员
        if(customerList != null && customerList.size() != 0) {
            customerUserIdList = sysDeptCustomerMapper.selectCustomerUserIdListByCustomerList(customerList);
        }
        List<MallOrder> mallOrderList = getMallOrderList(year, month, customerUserIdList);
        List<SpecialNameAndWeightVo> specialNameAndWeightVoList = mallOrderItemMapper.selectSpecialWeightByOrderList(mallOrderList, productType);
        List<SpecialNameAndWeightVo> copySpecialNameAndWeightVoList = new ArrayList<>();
        for(SpecialNameAndWeightVo specialNameAndWeightVo : specialNameAndWeightVoList){
            if(specialNameAndWeightVo.getQuantity().intValue() == 0) {
                continue;
            }
            copySpecialNameAndWeightVoList.add(specialNameAndWeightVo);
        }


        return ServerResponse.createBySuccess(copySpecialNameAndWeightVoList);

    }

    /**
     * @Date 2018/12/19 8:52
     * @Param [customerId, year, month]
     * @return java.util.List<com.hmall.model.MallOrder>
     * @Description  根据公司id得到与该公司有关的订单
     */
    private List<MallOrder> getOrderListByCustomerId(Integer customerId, Integer year, Integer month){
        List<Integer> customerUserIdList = sysDeptCustomerMapper.selectCustomerUserIdByCustomerId(customerId);
        List<MallOrder> orderList = getMallOrderList(year, month, customerUserIdList);
        return orderList;
    }

    /**
     * @Date 2018/12/19 8:28
     * @Param [customerId, year, month]
     * @return com.hmall.common.ServerResponse
     * @Description  根据公司得到公司相关的信息
     */
    public ServerResponse<BiTradeCustomerVo> getBiCustomerData(Integer customerId, Integer year, Integer month) {

        List<MallOrder> orderList = getOrderListByCustomerId(customerId, year, month);

        List<SpecialNameAndWeightVo> specialNameAndWeightVoList = new ArrayList<>();
        if(orderList != null && orderList.size() != 0) {
            specialNameAndWeightVoList = mallOrderItemMapper.selectProductNameAndWeight(orderList);
        }
        List<SpecialNameAndWeightVo> copySpecialNameAndWeightVoList = new ArrayList<>();
        for(SpecialNameAndWeightVo specialNameAndWeightVo : specialNameAndWeightVoList){
            //BigDecimal 为0 从数据库取出为0E-8
            if(specialNameAndWeightVo.getQuantity().intValue() == 0 || specialNameAndWeightVo.getQuantity().intValue() == 0E-8) {
                break;
            }
            copySpecialNameAndWeightVoList.add(specialNameAndWeightVo);
        }


        BiTradeVo biTradeVo = getBiTradeVo(orderList);

        BiTradeCustomerVo biTradeCustomerVo = new BiTradeCustomerVo();
        biTradeCustomerVo.setBiTradePaymentVoList(biTradeVo.getBiTradePaymentVoList());
        biTradeCustomerVo.setBiTradeWeightVoList(biTradeVo.getBiTradeWeightVoList());
        biTradeCustomerVo.setSpecialNameAndWeightVoList(copySpecialNameAndWeightVoList);

        return ServerResponse.createBySuccess(biTradeCustomerVo);
    }



}
